<template>
  <div class="container">
    <Breadcrumb />
    <a-card class="data-card">
      <a-button @click="openAdd(0)" type="primary">
        <template #icon>
          <icon-plus />
        </template>
        新增
      </a-button>
      <a-divider style="margin-top: 20px" />
      <a-table
        row-key="id"
        :loading="loading"
        :columns="columns"
        :data="renderData"
        :pagination="false"
        :bordered="false"
      >
        <template #option="{ record }">
          <a-space :size="18">
            <a-button
              @click="openAdd(record.id)"
              type="primary"
              v-if="record.parentId == 0"
            >
              添加下级
            </a-button>
            <a-button @click="openEdit(record)" type="outline"> 编辑 </a-button>
            <a-button status="danger" @click="openDelete(record)">
              删除
            </a-button>
          </a-space>
        </template>
      </a-table>
    </a-card>
    <a-modal
      v-model:visible="addShow"
      @cancel="handleCancel"
      :on-before-ok="handleCheck"
      :mask-closable="false"
      unmountOnClose
    >
      <template #title> 菜单 </template>
      <a-form ref="addModel" :rules="rules" :model="addForm">
        <a-form-item field="name" label="菜单名称">
          <a-input
            v-model="addForm.name"
            size="large"
            placeholder="请输入菜单名称"
          />
        </a-form-item>
        <a-form-item field="perms" label="权限编码">
          <a-input
            v-model="addForm.perms"
            size="large"
            placeholder="请输入权限编码"
          />
        </a-form-item>
        <a-form-item field="type" label="权限类型">
          <a-select
            v-model="addForm.type"
            :options="types"
            placeholder="请选择权限类型"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { computed, ref, reactive } from 'vue';
  import { Message, Modal } from '@arco-design/web-vue';
  import useLoading from '@/hooks/loading';
  import {
    permissionTree,
    permissionSave,
    permissionUpdate,
    permissionRemove,
  } from '@/api/permission.ts';
  import { useSelectionStore } from '@/store';
  import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';

  const { loading, setLoading } = useLoading(true);

  const generateDataModel = () => {
    return {
      id: '',
      parentId: '',
      name: '',
      perms: '',
      type: '',
    };
  };
  const rules = {
    name: [
      {
        required: true,
        message: '请输入菜单名称',
      },
      {
        maxLength: 20,
        message: '最长20位',
      },
    ],
    perms: [
      {
        required: true,
        message: '请输入权限编码',
      },
      {
        maxLength: 20,
        message: '最长20位',
      },
    ],
    type: [
      {
        required: true,
        message: '请选择权限类型',
      },
      {
        maxLength: 20,
        message: '最长20位',
      },
    ],
  };
  const addForm = ref(generateDataModel());
  const addShow = ref(false);
  const addModel = ref();

  const openAdd = (parentId) => {
    addShow.value = true;
    addForm.value = {
      ...generateDataModel(),
      parentId: parentId,
    };
  };

  const handleCheck = (done) => {
    if (loading.value) {
      done(false);
      return;
    }
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
    }, 1500);
    addModel.value.validate(
      async (errors: undefined | Record<string, ValidatedError>) => {
        if (!errors) {
          if (addForm.value.id) {
            permissionUpdate(addForm.value).then((res) => {
              if (res.code == '200') {
                Message.success({
                  //   content: res.message,
                  content: '编辑成功',
                });
                done(true);
                fetchData();
              } else {
                done(false);
              }
            });
          } else {
            permissionSave(addForm.value).then((res) => {
              if (res.code == '200') {
                Message.success({
                  //   content: res.message,
                  content: '新增成功',
                });
                done(true);
                fetchData();
              } else {
                done(false);
              }
            });
          }
        } else {
          done(false);
        }
      }
    );
  };

  const openEdit = (item) => {
    addForm.value = Object.assign({}, item);
    addShow.value = true;
  };

  const handleCancel = () => {
    addShow.value = false;
  };
  const openDelete = (item) => {
    Modal.confirm({
      title: '提示',
      content: '确认删除吗？',
      onOk() {
        permissionRemove({
          id: item.id,
        }).then((res) => {
          if (res.code == '200') {
            Message.success({
              //   content: res.message,
              content: '删除成功',
            });
            fetchData();
          }
        });
      },
    });
  };

  const columns = computed<TableColumnData[]>(() => [
    {
      title: '菜单名称',
      dataIndex: 'name',
    },
    {
      title: '权限编码',
      dataIndex: 'perms',
    },
    {
      title: '操作',
      dataIndex: 'option',
      slotName: 'option',
      align: 'center',
    },
  ]);

  const types = useSelectionStore().permissionTypes;

  const renderData = ref([]);

  const fetchData = async () => {
    setLoading(true);
    try {
      permissionTree().then((res) => {
        renderData.value = res.data;
      });
    } catch (err) {
      console.log(err);
    } finally {
      setLoading(false);
    }
  };

  fetchData();
</script>
